package cn.dw.web.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import Decoder.BASE64Decoder;
import cn.dw.domain.picCategory;
import cn.dw.domain.picInfo;
import cn.dw.service.PicCategoryService;
import cn.dw.service.PicInfoService;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
@WebService
public class picInfoAction extends ActionSupport implements ModelDriven<picInfo> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private PicInfoService pis;
	private PicCategoryService pcs;
	
	public JSONObject result;
	public Logger log = Logger.getLogger(getClass());
	@WebMethod(exclude=true)
	public void WriteLog(){
		HttpServletRequest request = ServletActionContext.getRequest();
		
		String ip = request.getHeader("x-forwarded-for");
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {     
            ip = request.getHeader("Proxy-Client-IP");      
        }     
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {     
            ip = request.getHeader("WL-Proxy-Client-IP");     
        }     
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {     
            ip = request.getRemoteAddr();      
        }
        
        System.out.println("ip===="+ip);
        log.info(ip);
	}
	
	public String getpicInfo(){
		
//		WriteLog();
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response1 = ServletActionContext.getResponse();
		
		response1.setContentType("application/json;charset=utf-8");
        response1.setHeader("Access-Control-Allow-Origin", "*");
		
		String categoryId = request.getParameter("categoryId");
        
//        String categoryId = "1";
//		System.out.println(categoryId);
		
		List<picInfo> picInfos = new ArrayList<picInfo>();
		picInfos.clear();
		if (categoryId.equals("0")) {
			picInfos = pis.getAll();
		} else {
			picInfos = pis.getInfosByCategoryId(categoryId);
		}
		
		
//		List<Map<String, Object>> picMaps = new ArrayList<Map<String,Object>>();
		Map<String, Object> map = null;
		int count = picInfos.size();
		List<picInfo> picInfos2 = new ArrayList<picInfo>();
		if (count>20) {
			List<Integer> ranodms = new ArrayList<Integer>();
			//取随机20个数
			while (ranodms.size()<=20) {
				int random = (int)(Math.random()*count);
				if (ranodms.size()==0) {
					ranodms.add(random);
//					System.out.println(random);
				} else {
					int state = 0;
					for(int j = 0; j < ranodms.size(); j++){
						if ((random==ranodms.get(j))) {
							state = 1;
							break;
						}
					}
					if (state==0) {
						ranodms.add(random);
//						System.out.println(random);
					}
				}
				
			}
			for(int i = 0; i < 20; i++){
				int random = ranodms.get(i);
				picInfos2.add(picInfos.get(random));
			}
			

			picInfos.clear();
			picInfos = picInfos2;
		}

		map = new HashMap<String, Object>();
		
		map.put("list", picInfos);
		JsonConfig jsonConfig = new JsonConfig();  //建立配置文件
        jsonConfig.setIgnoreDefaultExcludes(false);  //设置默认忽略
        jsonConfig.setExcludes(new String[]{"category"}); 
		JSONObject json = JSONObject.fromObject(map,jsonConfig);
		
		this.result = json;
		
		return "picInfo";
	}
	
	public String getDetailed() {
		
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response1 = ServletActionContext.getResponse();
		
		response1.setContentType("application/json;charset=utf-8");
        response1.setHeader("Access-Control-Allow-Origin", "*");
		
		String id = request.getParameter("id");
		picInfo pInfo = pis.getById(Integer.valueOf(id));
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("info", pInfo);
		
		JsonConfig jsonConfig = new JsonConfig();  //建立配置文件
        jsonConfig.setIgnoreDefaultExcludes(false);  //设置默认忽略
        jsonConfig.setExcludes(new String[]{"category"}); 
        JSONObject jo = JSONObject.fromObject(map,jsonConfig);
		
		this.result = jo;
		
		return "detailed";
	}

	public String upLoad(){
		
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response1 = ServletActionContext.getResponse();
		
		response1.setContentType("application/json;charset=utf-8");
        response1.setHeader("Access-Control-Allow-Origin", "*");
        picInfo pInfo = new picInfo();
        
        String title = request.getParameter("title");
        pInfo.setTitle(title);
        
        String categoryId = request.getParameter("categoryId");
        
        picCategory category = pcs.getById(Integer.valueOf(categoryId));
        
        pInfo.setCategory(category);
        
        String src0 = request.getParameter("src0");
        if (!src0.trim().equals("")) {
        	src0 = GenerateImage(src0, title);
        	pInfo.setSrc0(src0.substring(src0.indexOf("img")));
		}
        
        String desc1 = request.getParameter("desc1");
        pInfo.setDesc1(desc1);
        String src1 = request.getParameter("src1");
        if (!src1.trim().equals("")) {
        	src1 = GenerateImage(src1, title);
            pInfo.setSrc1(src1.substring(src1.indexOf("img")));
		}
        
        String src2 = request.getParameter("src2");
        if (!src2.trim().equals("")) {
        	src2 = GenerateImage(src2, title);
        	pInfo.setSrc2(src2.substring(src2.indexOf("img")));
		}
        
        String desc2 = request.getParameter("desc2");
        pInfo.setDesc2(desc2);
        String src3 = request.getParameter("src3");
        if (!src3.trim().equals("")) {
			src3 = GenerateImage(src3, title);
			pInfo.setSrc3(src3.substring(src3.indexOf("img")));
		}
        
        String desc3 = request.getParameter("desc3");
        pInfo.setDesc3(desc3);
        String desc4 = request.getParameter("desc4");
        pInfo.setDesc4(desc4);
        
        pis.save(pInfo);
        
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("info", "success");
        JsonConfig jsonConfig = new JsonConfig();  //建立配置文件
        jsonConfig.setIgnoreDefaultExcludes(false);  //设置默认忽略
        jsonConfig.setExcludes(new String[]{"category"}); 
        JSONObject jo = JSONObject.fromObject(map,jsonConfig);
		
		this.result = jo;
		
		return "upload";
	}
	
	//base64字符串转化成图片  
    public static String GenerateImage(String imgStr, String title)  
    {   //对字节数组字符串进行Base64解码并生成图片  
        if (imgStr == null) //图像数据为空  
            return "";
//        System.out.println(imgStr);
        String filename = imgStr.substring(0, imgStr.indexOf("data:image"));
        imgStr = imgStr.substring(imgStr.indexOf("base64,")+7);
        BASE64Decoder decoder = new BASE64Decoder();  
        try   
        {  
            //Base64解码  
            byte[] b = decoder.decodeBuffer(imgStr);  
            for(int i=0;i<b.length;++i)  
            {  
                if(b[i]<0)  
                {//调整异常数据  
                    b[i]+=256;  
                }  
            }  
            //生成jpeg图片
            String path = ServletActionContext.getServletContext().getRealPath("/img") + "\\" +title;
            File filepath = new File(path);
            if (!filepath.exists()) {
				filepath.mkdir();
			}
            String imgFilePath = path + "\\" + filename;//新生成的图片  
            OutputStream out = new FileOutputStream(imgFilePath);      
            out.write(b);  
            out.flush();  
            out.close();  
            return imgFilePath;  
        }   
        catch (Exception e){
        	e.printStackTrace();
            return "";  
        }  
    }  
	
	public PicInfoService getPis() {
		return pis;
	}

	public void setPis(PicInfoService pis) {
		this.pis = pis;
	}
	
	public PicCategoryService getPcs() {
		return pcs;
	}

	public void setPcs(PicCategoryService pcs) {
		this.pcs = pcs;
	}

	public JSONObject getResult() {
		return result;
	}

	public void setResult(JSONObject result) {
		this.result = result;
	}

	@Override
	public picInfo getModel() {
		// TODO Auto-generated method stub
		return null;
	}

}
